/**
 * Created by yuming619 on 2016/11/25.
 */
angular.module('mealplan.order', [])
    .config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {
        $stateProvider
            .state('mealplan.order', {
                url: '/order/list',
                templateUrl: mealplan_viewurl + "/order/order.html",
                controller: 'CmtOrderListController'
            })
            .state('mealplan.orderdetail', {
                url: '/order/list/{orderid}',
                templateUrl: mealplan_viewurl + "/order/detail.html",
                resolve: {
                    orderdetail_list: ['CmtOrderDetailService', '$stateParams', function (CmtOrderDetailService, $stateParams) {
                        return CmtOrderDetailService.getbyorderid($stateParams.orderid).$promise;
                    }]
                },
                controller: 'CmtOrderDetailController',
                params: {
                    order: null
                }
            })
            .state('mealplan.ordersend', {
                url: '/order/send',
                templateUrl: mealplan_viewurl + "/order/order_send.html",
                resolve: {
                    order_list: ['CmtOrderService', function (CmtOrderService) {
                        return CmtOrderService.getstate(0, 1, null, null).$promise;
                    }]
                },
                controller: 'CmtOrderSendController'
            })
    }])

    .controller('CmtOrderListController', ['$scope', '$cookieStore', 'CmtOrderService', '$filter', function ($scope, $cookieStore, CmtOrderService, $filter) {

        var d = new Date();
        $scope.start_time_show = d.getFullYear() + "-" + (d.getMonth() - 1) + "-" + d.getDate();
        $scope.end_time_show = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + (d.getDate() + 1);

        var e = new Date($scope.end_time_show.replace(/-/g, '/'));
        var s = new Date($scope.start_time_show.replace(/-/g, '/'));
        $scope.start_time = s.getTime();
        $scope.end_time = e.getTime();
        //
        prepare_order(null, null, $scope.start_time, $scope.end_time);

        //all order
        $scope.status;
        $scope.paystate;
        function prepare_order(status, paystate, time_start, time_end) {
            CmtOrderService.getstate(status, paystate, time_start, time_end).$promise.then(function (data) {
                // var order_list = data;
                $scope.orders = data;
            })
        }

        $scope.orderbytime = function () {
            $scope.status = null;
            $scope.paystate = null
            prepare_order($scope.status, $scope.paystate, $scope.start_time, $scope.end_time);
        }

        $scope.orderbystatus = function (status) {
            $scope.status = status;
            $scope.paystate = null;
            prepare_order($scope.status, $scope.paystate, $scope.start_time, $scope.end_time);
        }
        $scope.orderbypaystate = function (paystate) {
            $scope.paystate = paystate;
            $scope.status = null;
            prepare_order($scope.status, $scope.paystate, $scope.start_time, $scope.end_time);
        }

        $scope.changeOrder = function () {
            prepare_order($scope.status, $scope.paystate, $scope.start_time, $scope.end_time);
        }

        $scope.selectbyid = function (id) {
            if (id === undefined) {
                alert("请输入搜素条件！");
                return;
            } else {
                if (id.length == 8) {
                    CmtOrderService.selectbyid(id).$promise.then(function (data) {
                        $scope.orders = [];
                        $scope.orders.push(data);
                    })
                } else {
                    CmtOrderService.getbybuyid(id).$promise.then(function (data) {
                        $scope.orders = data;
                    })
                }
            }
        }

        $('#datetimepicker').datetimepicker({
            format: "yyyy-MM-dd hh:ii",
            autoclose: true,
            todayBtn: true,
            pickerPosition: "bottom-left"
        }).on('changeDate', function (ev) {
            $scope.start_time = ev.date.valueOf();
            //console.log(ev.date.valueOf());
        });
        $('#datetimepicker1').datetimepicker({
            format: "yyyy-MM-dd hh:ii",
            autoclose: true,
            todayBtn: true,
            pickerPosition: "bottom-left"
        }).on('changeDate', function (ev) {
            $scope.end_time = ev.date.valueOf();
            // console.log($scope.end_time);
            //console.log(ev.date.valueOf());
        });

        $scope.remove = function (order) {
            var index = $scope.orders.indexOf(order);
            if (index > -1) {
                $scope.orders.splice(index, 1);
            }
            CmtOrderService.deletebyid(order.orderid).$promise.then(function (data) {
                alert("删除成功！");
            })
        }

        //timestamp to date
        function timeConverter(UNIX_timestamp) {
            if (UNIX_timestamp == undefined || UNIX_timestamp == "") {
                return '';
            }
            var a = new Date(UNIX_timestamp);
            var year = a.getFullYear();
            var month = a.getMonth();
            var date = islow10(a.getDate());
            var hour = islow10(a.getHours());
            var min = islow10(a.getMinutes());
            var sec = islow10(a.getSeconds());
            //
            function islow10(time) {
                if (time < 10) {
                    time = '0' + time;
                }
                return time
            }

            var time = year + '-' + month + '-' + date + ' ' + hour + ':' + min + ':' + sec;
            return time;
        }

        //导出订单
        /* $scope.alert_msg = "";
         $scope.close_alert = function () {
         $scope.alert_msg = "";
         }

         $scope.export_orders = function (orders) {
         $scope.alert_msg = "订单导出时间较久，please wait !";
         //ready
         var name = "农归吧订单 " + timeConverter(new Date().getTime());
         var exportdata = [];
         var firstdata = [
         '订单id', '总金额', '订单留言', '下单时间', '订单更新时间',
         '实际金额', '订单状态', '支付状态', '订单类型', '收货人', '收货电话',
         '邮编', '收货地址', '用户', '支付类型', '商品id', '商品名称',
         '商品单价', '购买数量', '商店id', '商店名称'
         ];
         exportdata.push(firstdata);
         //get for order detail
         var orderlist = {
         orders: []
         }
         orderlist.orders = orders;
         CmtOrderService.getorderdetail(orderlist, function (result) {
         var totalOrder = result;
         for (var i = 0; i < totalOrder.length; i++) {
         var order = totalOrder[i].order;
         var orderDetailsList = totalOrder[i].respOrderDetails;
         for (var j = 0; j < orderDetailsList.length; j++) {
         var nextdata = [];
         var orderDetail = orderDetailsList[j];
         //order
         for (value in order) {
         if (value == 'createTime' || value == 'updateTime') {
         nextdata.push(timeConverter(order[value]));
         } else if (value == 'type') {
         nextdata.push($filter('order_type')(order[value]));
         } else if (value == 'status') {
         nextdata.push($filter('order_status')(order[value]));
         } else if (value == 'paystate') {
         nextdata.push($filter('pay_type')(order[value]));
         } else if (value == 'paytype') {
         nextdata.push($filter('order_paytype')(null, order[value], null));
         } else if (value != '__proto__' && value != '$$hashKey' && typeof order[value] != 'function' && value != 'logo' && value != 'nickname' && value != 'buyerid') {
         nextdata.push(order[value]);
         }
         }
         //ordedetail
         for (value in orderDetail) {
         if (value != '__proto__' && value != '$$hashKey' && typeof orderDetail[value] != 'function' && value != 'goodsLogo') {
         nextdata.push(orderDetail[value]);
         }
         }
         exportdata.push(nextdata);
         }
         }
         //export
         ExportSaveAs.export_excel(exportdata, name);
         $scope.alert_msg = "";
         }, function (data) {
         alert("导出失败");
         })

         }*/


    }])

    .controller('CmtOrderDetailController', ['$scope', '$stateParams', 'ServiceItemService', 'ServiceTopService', 'orderdetail_list', function ($scope, $stateParams, ServiceItemService, ServiceTopService, orderdetail_list) {
        $scope.orderdetails = orderdetail_list;
        // console.log(orderdetail_list);
        if ($stateParams.order != null) {
            for (var i = 0; i < $scope.orderdetails.length; i++) {
                $scope.orderdetails[i].buyname = $stateParams.order.name;
                $scope.orderdetails[i].status = $stateParams.order.status;
                $scope.orderdetails[i].paystate = $stateParams.order.paystate;
                $scope.orderdetails[i].type = $stateParams.order.type;
                $scope.orderdetails[i].buyMessage = $stateParams.order.buyMessage;
            }
        }
        // console.log($stateParams.order);
        var serviceitem_map = {};
        var service_map = {};
        $scope.prepare_data = function (orderid, serviceitemid, serviceid) {
            var orderdetail = {};
            for (var i = 0; i < $scope.orderdetails.length; i++) {
                if ($scope.orderdetails[i].orderid == orderid && $scope.orderdetails[i].serviceitemid == serviceitemid
                    && $scope.orderdetails[i].serviceid == serviceid) {
                    orderdetail = $scope.orderdetails[i];
                    break;
                }
            }
            //
            if (serviceitem_map[serviceitemid]) {
                orderdetail.serverItemName = serviceitem_map[serviceitemid];
            } else {
                ServiceItemService.getbyid(serviceitemid).$promise.then(function (data) {
                    service_map[serviceitemid] = data.name;
                    orderdetail.serverItemName = data.name;
                })
            }
            if (service_map[serviceid]) {
                orderdetail.serverName = service_map[serviceid];
            } else {
                ServiceTopService.getbyid(serviceid).$promise.then(function (data) {
                    service_map[serviceid] = data.name;
                    orderdetail.serverName = data.name;
                })
            }
        }


    }])

    .controller('CmtOrderSendController', ['$scope', 'CmtOrderService', 'order_list', function ($scope, CmtOrderService, order_list) {
        $scope.orders = order_list;
        $scope.update = function (order) {
            var index = $scope.orders.indexOf(order);
            if (index > -1) {
                $scope.orders.splice(index, 1);
            }
            order.status = 1;
            CmtOrderService.update(order.orderid, order, function (data) {
                alert("发货成功！");
                // window.location.reload();
            }, function () {
                alert("发货失败！");
            })
        }
    }])
;